package com.aiyige.page.edituserinfo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.city.model.City;
import com.aiyige.model.User;
import com.aiyige.model.UserCertification;
import com.aiyige.page.authentication.OrganizationAuthenticationPage;
import com.aiyige.page.authentication.model.Authentication;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ColorUtil;
import com.aiyige.utils.DateFormatUtil;
import com.aiyige.utils.DummyDataUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UploadPhotoUtil;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import timber.log.Timber;

@Route(path = ARouterConfig.EditUserInfoPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class EditUserInfoPage extends AppCompatActivity {
    @BindView(R.id.avatarIv)
    ImageView avatarIv;
    @BindView(R.id.userNameTv)
    TextView userNameTv;
    @BindView(R.id.sexTv)
    TextView sexTv;
    @BindView(R.id.birthdayTv)
    TextView birthdayTv;
    @BindView(R.id.addressTv)
    TextView addressTv;
    @BindView(R.id.titleTv)
    TextView titleTv;
    UserSexBottomDialog userSexBottomDialog;
    @BindView(R.id.authenticationTv)
    TextView authenticationTv;
    @BindView(R.id.authenticationIv)
    ImageView authenticationIv;
    @BindView(R.id.loadingLayout)
    View loadingLayout;
    @BindView(R.id.errorLayout)
    View errorLayout;
    Authentication authentication;
    boolean firstEnter = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_edit_user_info);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        titleTv.setText(R.string.edit_user_info);
        userSexBottomDialog = UserSexBottomDialog.newInstance();
    }


    @Override
    protected void onResume() {
        super.onResume();
        Glide.with(this)
                .load(AccountUtil.getCurrentUser().getAvatar())
                .apply(RequestOptions.placeholderOf(R.drawable.default_head))
                .apply(RequestOptions.circleCropTransform())
                .into(avatarIv);
        userNameTv.setText(AccountUtil.getCurrentUser().getAccount());
        switch (AccountUtil.getCurrentUser().getMoreBackup().getSex()) {
            case User.GENDER_FEMALE:
                sexTv.setText(StringUtils.getString(R.string.female));
                userSexBottomDialog.setSex(UserSexBottomDialog.FEMALE);
                break;
            case User.GENDER_MALE:
                sexTv.setText(StringUtils.getString(R.string.male));
                userSexBottomDialog.setSex(UserSexBottomDialog.MALE);
                break;
            default:
                sexTv.setText(StringUtils.getString(R.string.unknown));
                userSexBottomDialog.setSex(UserSexBottomDialog.UNKNOWN);
                break;
        }

        birthdayTv.setText(DateFormatUtil.formatMS("yyyy.MM.dd", AccountUtil.getCurrentUser().getMoreBackup().getBirthDate()));

        City city = DummyDataUtil.getCityById(AccountUtil.getCurrentUser().getMoreBackup().getCity());
        if (city == null) {
            city = new City();
        }
        addressTv.setText((TextUtils.isEmpty(city.getProvince()) ? "" : city.getProvince()) + " " + (TextUtils.isEmpty(city.getCity()) ? "" : city.getCity()));
        userSexBottomDialog.setListener(new UserSexBottomDialog.Listener() {
            @Override
            public void onClick(int sex) {
                String userGender;
                switch (sex) {
                    case UserSexBottomDialog.MALE:
                        userGender = User.GENDER_MALE;
                        break;
                    case UserSexBottomDialog.FEMALE:
                        userGender = User.GENDER_FEMALE;
                        break;
                    default:
                        userGender = User.GENDER_UNKNOWN;
                        break;
                }
                ApiManager.getService().userCenterUsers(AccountUtil.getCurrentUser().getId(), User.newBuilder()
                        .moreBackup(User.MoreBackup.newBuilder()
                                .sex(userGender)
                                .build())
                        .build())
                        .enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                try {
                                    if (response.code() != ResponseCode.CREATED) {
                                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                    }
                                    String json = RetrofitUtil.getResponseBodyAsString(response);
                                    User tempUser = JSON.parseObject(json, User.class);
                                    User user = AccountUtil.getCurrentUser();
                                    user.getMoreBackup().setSex(tempUser.getMoreBackup().getSex());
                                    AccountUtil.updateCurrentUser(user);
                                    switch (AccountUtil.getCurrentUser().getMoreBackup().getSex()) {
                                        case User.GENDER_FEMALE:
                                            sexTv.setText(StringUtils.getString(R.string.female));
                                            break;
                                        case User.GENDER_MALE:
                                            sexTv.setText(StringUtils.getString(R.string.male));
                                            break;
                                        default:
                                            sexTv.setText(StringUtils.getString(R.string.unknown));
                                            break;
                                    }
                                    ToastX.show(R.string.edit_user_gender_success);
                                } catch (Exception e) {
                                    onFailure(call, e);
                                }
                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                ToastX.show(t.getMessage());
                            }
                        });
            }
        });
        if (firstEnter) {
            requestData(true);
            firstEnter = false;
        } else {
            requestData(false);
        }
    }

    public void requestData(boolean showLoading) {
        new RequestDataTask(this, showLoading).execute();
    }


    public void showLoadingLayout() {
        loadingLayout.setVisibility(View.VISIBLE);
        errorLayout.setVisibility(View.VISIBLE);
    }

    public void showErrorLayout() {
        loadingLayout.setVisibility(View.INVISIBLE);
        errorLayout.setVisibility(View.VISIBLE);
    }

    public void hideCoverLayout() {
        loadingLayout.setVisibility(View.INVISIBLE);
        errorLayout.setVisibility(View.INVISIBLE);
    }


    @OnClick({R.id.errorLayout, R.id.authenticationLayout, R.id.editInterestLayout, R.id.avatarIv, R.id.avatarLayout, R.id.userNameLayout, R.id.sexLayout, R.id.birthdayLayout, R.id.addressLayout, R.id.titleBackBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.errorLayout:
                requestData(true);
                break;
            case R.id.authenticationLayout: {
                switch (authentication.getAuditStatus()) {
                    case Authentication.STATUS_AUTHENTICATION_SUCCESS: {
                        switch (authentication.getUserType()) {
                            case Authentication.USER_TYPE_ORGANIZATION:
                                ARouter.getInstance()
                                        .build(ARouterConfig.OrganizationAuthenticationPage)
                                        .withParcelable("authentication", authentication)
                                        .navigation();
                                break;
                            case Authentication.USER_TYPE_PERSONAL:
                                ARouter.getInstance()
                                        .build(ARouterConfig.PersonalAuthenticationPage)
                                        .withParcelable("authentication", authentication)
                                        .navigation();
                                break;
                        }
                        break;
                    }
                    case Authentication.STATUS_WAITING_AUTHENTICATION:
                        ARouter.getInstance()
                                .build(ARouterConfig.WaitingAuthenticationPage)
                                .navigation();
                        break;
                    case Authentication.STATUS_AUTHENTICATION_FAILED:
                        ARouter.getInstance()
                                .build(ARouterConfig.AuthenticationFailedPage)
                                .withParcelable("authentication", authentication)
                                .navigation();
                        break;
                    case Authentication.STATUS_NOT_AUTHENTICATION:
                        ARouter.getInstance()
                                .build(ARouterConfig.SelectAuthenticationMethodPage)
                                .navigation();
                        break;
                }
                break;
            }
            case R.id.avatarIv:
                ARouter.getInstance()
                        .build(ARouterConfig.PhotoViewPage)
                        .withString("photoUrl", AccountUtil.getCurrentUser().getAvatar())
                        .navigation();
                break;
            case R.id.avatarLayout:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .imageSpanCount(4)
                        .selectionMode(PictureConfig.SINGLE)
                        .previewImage(true)
                        .isCamera(true)
                        .enableCrop(true)
                        .sizeMultiplier(0.5f)
                        .withAspectRatio(1, 1)
                        .freeStyleCropEnabled(false)
                        .circleDimmedLayer(true)
                        .previewEggs(true)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.userNameLayout:
                ARouter.getInstance().build(ARouterConfig.EditUserNamePage).navigation();
                break;
            case R.id.sexLayout:
                userSexBottomDialog.show(getSupportFragmentManager(), "");
                break;
            case R.id.birthdayLayout: {
                Calendar selectedDate = Calendar.getInstance();
                Calendar startDate = Calendar.getInstance();
                startDate.set(startDate.get(Calendar.YEAR) - 120, Calendar.JANUARY, 1);
                if (AccountUtil.getCurrentUser().getMoreBackup().getBirthDate() != null && AccountUtil.getCurrentUser().getMoreBackup().getBirthDate() != 0) {
                    selectedDate.setTimeInMillis(AccountUtil.getCurrentUser().getMoreBackup().getBirthDate());
                }
                Calendar endDate = Calendar.getInstance();
                //时间选择器
                TimePickerView pickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        ApiManager.getService()
                                .userCenterUsers(String.valueOf(AccountUtil.getCurrentUser().getId()), User.newBuilder().moreBackup(User.MoreBackup.newBuilder().birthDate(date.getTime()).build()).build())
                                .enqueue(new Callback<ResponseBody>() {
                                    @Override
                                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                        try {
                                            if (response.code() != ResponseCode.CREATED) {
                                                throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                            }
                                            String json = RetrofitUtil.getResponseBodyAsString(response);
                                            User tempUser = JSON.parseObject(json, User.class);
                                            User user = AccountUtil.getCurrentUser();
                                            user.getMoreBackup().setBirthDate(tempUser.getMoreBackup().getBirthDate());
                                            AccountUtil.updateCurrentUser(user);
                                            birthdayTv.setText(DateFormatUtil.formatMS("yyyy.MM.dd", user.getMoreBackup().getBirthDate()));
                                            ToastX.show(R.string.edit_user_birthday_success);
                                        } catch (Exception e) {
                                            onFailure(call, e);
                                        }
                                    }

                                    @Override
                                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                                        ToastX.show(t.getMessage());
                                    }
                                });
                    }
                })
                        //年月日时分秒 的显示与否，不设置则默认全部显示
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setSubmitText(getString(R.string.finish))
                        .setTitleBgColor(Color.WHITE)
                        .setBgColor(0xfff0f0f0)
                        .setLabel("", "", "", "", "", "")
                        .isCenterLabel(false).setSubmitColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setCancelColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                        .setDividerColor(Color.DKGRAY)
                        .setContentSize(21)
                        .setDate(selectedDate)
                        .setRangDate(startDate, endDate)
                        .isDialog(true)
                        .build();
                pickerView.show();
                break;
            }
            case R.id.addressLayout:
                ARouter.getInstance().build(ARouterConfig.EditUserAddressPage).navigation();
                break;
            case R.id.editInterestLayout:
                ARouter.getInstance().build(ARouterConfig.EditUserInterestPage).navigation();
                break;
            case R.id.titleBackBtn:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia item : selectList) {
                        final String path;
                        if (item.isCompressed()) {
                            path = item.getCompressPath();
                        } else if (item.isCut()) {
                            path = item.getCutPath();
                        } else {
                            path = item.getPath();
                        }

                        UploadPhotoUtil.newBuilder()
                                .photoLocalUrl(path)
                                .listener(new UploadPhotoUtil.Listener() {
                                    LoadingDialog loadingDialog;

                                    @Override
                                    public void onPreUpload() {
                                        loadingDialog = LoadingDialog.newBuilder()
                                                .with(EditUserInfoPage.this)
                                                .message(R.string.uploading)
                                                .show();
                                    }

                                    @Override
                                    public void onProgress(double progress) {
                                        Timber.e("onProgress:" + progress);
                                    }

                                    @Override
                                    public void onFail(Throwable t) {
                                        ToastX.show(t.getMessage());
                                        loadingDialog.dismiss();
                                    }

                                    @Override
                                    public void onFinish(String url) {
                                        Timber.e("onFinish:" + url);
                                        ApiManager.getService()
                                                .userCenterUsers(AccountUtil.getCurrentUser().getId(), User.newBuilder().avatar(url).build())
                                                .enqueue(new Callback<ResponseBody>() {
                                                    @Override
                                                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                                        try {
                                                            if (response.code() != ResponseCode.CREATED) {
                                                                throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                                            }
                                                            String json = RetrofitUtil.getResponseBodyAsString(response);
                                                            User tempUser = JSON.parseObject(json, User.class);
                                                            User user = AccountUtil.getCurrentUser();
                                                            user.setAvatar(tempUser.getAvatar());
                                                            AccountUtil.updateCurrentUser(user);
                                                            Glide.with(EditUserInfoPage.this)
                                                                    .load(user.getAvatar())
                                                                    .apply(RequestOptions.circleCropTransform())
                                                                    .into(avatarIv);
                                                            loadingDialog.dismiss();
                                                            ToastX.show(R.string.edit_user_avatar_success);
                                                        } catch (Exception e) {
                                                            onFailure(call, e);
                                                        }
                                                    }

                                                    @Override
                                                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                                                        ToastX.show(t.getMessage());
                                                        loadingDialog.dismiss();
                                                    }
                                                });
                                    }
                                })
                                .build()
                                .upload();
                    }
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }


    public void clearAuthenticationView() {
        authenticationIv.setVisibility(View.GONE);
        authenticationTv.setVisibility(View.GONE);
    }

    public void updateAuthenticationView() {
        switch (authentication.getAuditStatus()) {
            case Authentication.STATUS_NOT_AUTHENTICATION:
                authenticationIv.setVisibility(View.GONE);
                authenticationTv.setVisibility(View.VISIBLE);
                authenticationTv.setText(R.string.not_submit_authentication);
                break;
            case Authentication.STATUS_AUTHENTICATION_FAILED:
                authenticationTv.setText(R.string.authentication_failed);
                authenticationTv.setVisibility(View.VISIBLE);
                authenticationIv.setVisibility(View.GONE);
                break;
            case Authentication.STATUS_AUTHENTICATION_SUCCESS: {
                switch (authentication.getUserType()) {
                    case Authentication.USER_TYPE_ORGANIZATION:
                        authenticationIv.setVisibility(View.VISIBLE);
                        authenticationIv.setImageResource(R.drawable.identity_enterprise);
                        authenticationTv.setVisibility(View.VISIBLE);
                        authenticationTv.setText(authentication.getCompanyName());
                        break;
                    case Authentication.USER_TYPE_PERSONAL:
                        authenticationIv.setVisibility(View.VISIBLE);
                        authenticationIv.setImageResource(R.drawable.identity_personal);
                        authenticationTv.setVisibility(View.VISIBLE);
                        authenticationTv.setText(authentication.getPersonalName());
                        break;
                    default:
                        authenticationIv.setVisibility(View.GONE);
                        authenticationTv.setVisibility(View.GONE);
                        break;

                }
                break;
            }
        }


    }

    public class RequestDataTask extends SafeAsyncTask<Object, Object, Object> {
        boolean showLoading;

        public RequestDataTask(Activity activity, boolean showLoading) {
            super(activity);
            this.showLoading = showLoading;
            if (showLoading) {
                showLoadingLayout();
            }
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                if (showLoading) {
                    showErrorLayout();
                }
                ToastX.show((Exception) o);
                clearAuthenticationView();
            } else {
                if (showLoading) {
                    hideCoverLayout();
                }
                authentication = (Authentication) o;
                updateAuthenticationView();
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().getUserAuthenticationInfo().execute();
                if (response.code() == ResponseCode.NOT_FOUND) {
                    return Authentication.newBuilder()
                            .readOnly(false)
                            .userType(Authentication.USER_TYPE_UNKNOW)
                            .auditStatus(Authentication.STATUS_NOT_AUTHENTICATION)
                            .build();
                } else if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                } else {
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    UserCertification userCertification = JSON.parseObject(json, UserCertification.class);
                    return Authentication.parse(userCertification);
                }
            } catch (Exception e) {
                return e;
            }
        }
    }
}
